package tail;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

/**
 * @author Michael Sena
 * @version 1.0
 */
public class Tail extends Thread {

    /**
     * Holds a buffer for the file.
     */
    private BufferedInputStream buffer = null;
    /**
     * Minimum amount of time that will be waited in between file reads.
     */
    private static final int MIN_WAIT_TIME = 100;
    /**
     * Maximum amount of time waited in between file reads.
     */
    private static final int MAX_WAIT_TIME = 5000;
    /**
     * The amount to wait in-between threads.
     */
    private static final int INITIAL_WAIT_TIME = 500;
    /**
     * Holds input bytes from the file.
     */
    private byte[] bytes = null;
    /**
     * Dynamic waiting amount time; changes based on frequency of r/w to file.
     */
    private int dynamicWaitTime = INITIAL_WAIT_TIME;
    /**
     * Assists in dynamically adjusting the file r/w amount.
     */
    private int dataLoadInt = 0;

    /**
     * Stream to which data will be displayed.
     */
    private JTextArea output = null;

    /**
     * Default constructor.
     * @param file Filename to tail
     */
    public Tail(final String file) {
        try {
            buffer = new BufferedInputStream(new FileInputStream(file));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Tail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Uses a JTextArea as the output instead of standard output.
     * @param file Filename to tail
     * @param textArea JTextArea object to output to
     */
    public Tail(final String file, final JTextArea textArea) {
        this(file);
        output = textArea;
    }

    /**
     * Reads new available data from the file and places it into the buffer.
     */
    private void readUpTo() {
        try {
            bytes = new byte[buffer.available()];
            buffer.read(bytes);
        } catch (IOException ex) {
            Logger.getLogger(Tail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Displays buffered data.
     */
    private void displayData() {
        if (bytes != null && bytes.length > 0) {
            char[] result = new char[bytes.length];
            for (int i = 0; i < bytes.length; i++) {
                result[i] = (char) bytes[i];
            }
            if (output == null) {
                System.out.print(result);
            } else {
                output.append(String.copyValueOf(result));
            }
            bytes = null;
        }
    }

    /**
     * Decreases the waiting time between file reading.
     */
    private void decWaitTime() {
        if (dataLoadInt == 1 && dynamicWaitTime > MIN_WAIT_TIME) {
            dynamicWaitTime /= 2;
            if (dynamicWaitTime < MIN_WAIT_TIME) {
                dynamicWaitTime = MIN_WAIT_TIME;
            }
        } else if (dataLoadInt < 1) {
            dataLoadInt++;
        }
    }

    /**
     * Increases the waiting time between file reading.
     */
    private void incWaitTime() {
        if (dataLoadInt == -1 && dynamicWaitTime < MAX_WAIT_TIME) {
            dynamicWaitTime *= 2;
            if (dynamicWaitTime > MAX_WAIT_TIME) {
                dynamicWaitTime = MAX_WAIT_TIME;
            }
        } else if (dataLoadInt > -1) {
            dataLoadInt--;
        }
    }

    @Override
    /**
     * Starts the thread and acts as the main function.
     */
    public final void run() {
        synchronized (this) {
            try {
                // Loop while the thread is alive
                while (this.isAlive()) {
                    // Read bytes if any are available
                    if (buffer.available() > 0) {
                        // Read all available bytes at once
                        while (buffer.available() > 0) {
                            // Read and display available data
                            readUpTo();
                            displayData();
                        }
                        // Decrease the wait time
                        decWaitTime();
                    } else {
                        // Increase the wait time
                        incWaitTime();
                    }

                    // Pause for an amount of time
                    wait(dynamicWaitTime);
                }
            } catch (InterruptedException ex) {
                log(ex);
            } catch (IOException ex) {
                log(ex);
            }
        }
    }

    /**
     * Standard error logging function.
     * @param ex Exception raised
     */
    private void log(final Exception ex) {
        Logger.getLogger(Tail.class.getName()).log(Level.SEVERE, null, ex);
    }

    /**
     * Initiating function.
     * @param args Command line arguments
     */
    public static void main(final String[] args) {
        // Check for the correct number of arguments
        if (args.length != 1) {
            System.out.println("Usage: tail.jar [filename]");
            System.exit(0);
        }

        // Start the tail function
        Tail main = new Tail(args[0]);
        main.start();
    }
}
